import json
import pymysql
import traceback

# 数据库配置
host = '127.0.0.1'
user = 'fwq'
password = '123456'
database = 'paper'
charset = 'utf8mb4'  # 支持更全的字符集（如 emoji）


def insert_gitee_project(i,title, stars, forks, desc, labels, license, submit_times, last_submit):
    """
    插入 Gitee 项目数据到 MySQL
    """
    conn = pymysql.connect(
        host=host,
        user=user,
        password=password,
        database=database,
        charset=charset,
        autocommit=True,  # 自动提交事务
    )
    cursor = conn.cursor()

    # 插入 SQL 语句
    sql = """
    INSERT INTO projects 
    (id,title, stars, forks, description, labels, license, submit_times, last_submit)
    VALUES (%s,%s, %s, %s, %s, %s, %s, %s, %s)
    """

    # 参数（labels 转为逗号分隔的字符串）
    params = (i,
        title,
        stars,
        forks,
        desc,
        ",".join(labels) if labels else "",  # 关键点：列表转字符串
        license,
        submit_times,
        last_submit
    )

    # 执行插入
    try:
        cursor.execute(sql, params)
        print(f"插入成功：{title}")
    except Exception as e:
        print(f"插入失败：{title}")
        print("错误详情：", e)
        print(traceback.format_exc())
    finally:
        cursor.close()
        conn.close()


def main():
    # 1. 读取 JSON 文件
    with open('python_projects.json', 'r', encoding='utf-8') as f:
        projects = json.load(f)
    i=730
    # 2. 逐条插入数据库
    for project in projects:
        i=i+1
        insert_gitee_project(
            i,
            title=project['title'],
            stars=project['stars'],
            forks=project['forks'],
            desc=project['desc'],
            labels=project['labels'],
            license=project['license'],
            submit_times=project['submit_times'],
            last_submit=project['last_submit']
        )


if __name__ == "__main__":
    main()

import requests
def set_gpu():
    import os
    import pynvml
    try:
        # 初始化 NVIDIA 管理库
        pynvml.nvmlInit()
        # 获取 GPU 设备数量
        gpu_count = pynvml.nvmlDeviceGetCount()
        min_utlization = 100
        idlist = []
        min_id=1;
        # 遍历所有 GPU 设备
        for gpu_id in range(gpu_count):
            handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
            # 获取 GPU 信息
            gpu_utilization = (int)(pynvml.nvmlDeviceGetUtilizationRates(handle).gpu)
            if(gpu_utilization<min_utlization):
                min_utlization = gpu_utilization
                min_id=gpu_id
            if(gpu_utilization<20):
                idlist.append(gpu_id)
        #设置
        if (len(idlist) == 0):
            idlist.append(min_id)
        os.environ["CUDA_VISIBLE_DEVICES"] = ','.join(map(str, idlist))
        # 释放 NVIDIA 管理库
        pynvml.nvmlShutdown()
        return min_id,idlist
    except pynvml.NVMLError as error:
        print(f"NVIDIA Management Library Error: {error}")